import 'dart:async';

import 'package:shared_preferences/shared_preferences.dart';

///  ***************************************************************************
///  数据存储的工具类 单例模式
///  ***************************************************************************

class SpUtil {
  static final SpUtil _spUtils = SpUtil._internal();

  factory SpUtil() {
    return _spUtils;
  }

  SpUtil._internal();

  ///数据字符串键值对数据
  Future saveByKey(String key, var value) async {
    if (value == null) {
      return;
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await _saveValue(prefs, key, value);
  }

  ///添加数据
  Future saveByMap(Map map) async {
    if (map == null || map.length == 0) {
      return;
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await map.forEach((key, value) {
      _saveValue(prefs, key, value);
    });
  }

  ///获取字符串数据
  Future getString(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String value = await prefs.getString(key);
    return value;
  }

  ///获取boolan数据
  Future getBoolean(String key, bool defalutValue) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    bool value = await prefs.getBool(key);
    if (value == null) {
      return defalutValue;
    }

    return value;
  }

  ///获取键值对都为字符串数据的Map
  Future getStrMapByList(List<String> keys) async {
    if (keys == null || keys.length == 0) {
      return null;
    }

    SharedPreferences prefs = await SharedPreferences.getInstance();
    Map<String, String> result = Map();

    for (String key in keys) {
      String value = await prefs.getString(key);
      result.putIfAbsent(key, () => value);
    }

    return result;
  }

  ///根据key值删除数据
  void removeByKey(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove(key);
  }

  ///更Key的列表删除数据
  void removeByList(List<String> keys) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    for (String key in keys) {
      await prefs.remove(key);
    }
  }

  _saveValue(SharedPreferences prefs, String key, var value) async {
    if (key == null || key.length == 0 || value == null) {
      return;
    }

    if (value is String) {
      await prefs.setString(key, value);
      return;
    }

    if (value is int) {
      await prefs.setInt(key, value);
      return;
    }

    if (value is double) {
      await prefs.setDouble(key, value);
    }

    if (value is bool) {
      await prefs.setBool(key, value);
    }

    if (value is List<String>) {
      await prefs.setStringList(key, value);
    }
  }
}
